﻿using CorrectTowerHeightTool.Model;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CorrectTowerHeightTool.Bll
{
    public class TowerHeightBll
    {
        public TowerHeight[] ParseExcel(string excel) 
        {
            List<TowerHeight> towerHeights = new List<TowerHeight>();
            #region check file if exists
            FileStream stream = null;
            try
            {
                stream = File.OpenRead(excel);
            }
            catch (IOException ex)
            {
                //MessageBox.Show(ex.Message);
                throw new IOException();
            }
            #endregion


            #region read excel
            using (stream)
            {
                ExcelPackage package = new ExcelPackage(stream);

                ExcelWorksheet sheet = package.Workbook.Worksheets[1];
                #region check excel format
                if (sheet == null)
                {
                    //MessageBox.Show("Excel format error!");
                    //return;
                    throw new Exception();
                }
                if (!sheet.Cells[1, 1].Value.ToString().Contains("杆塔号") ||
                     !sheet.Cells[1, 2].Value.Equals("地线高度") ||                  
                        !sheet.Cells[1, 3].Value.Equals("图像名"))
                {
                    //MessageBox.Show("Excel format error!");
                    //return;
                    throw new Exception("Excel format error!");
                }
                #endregion

                #region get last row index
                int lastRow = sheet.Dimension.End.Row;
                while (sheet.Cells[lastRow, 1].Value == null)
                {
                    lastRow--;
                }
                #endregion

                #region read datas
                for (int i = 2; i <= lastRow; i++)
                {
                    TowerHeight point = new TowerHeight();
                    point.towerNo = sheet.Cells[i, 1].Value.ToString();
                    if (sheet.Cells[i, 2].Value!=null)
                    {
                        point.height = double.Parse(sheet.Cells[i, 2].Value.ToString());
                    }
                    if (sheet.Cells[i, 3].Value != null)
                    {
                        point.img = sheet.Cells[i, 3].Value.ToString();
                    }                   
                    towerHeights.Add(point);


                }
                #endregion

            }
            #endregion

            return towerHeights.ToArray();
        }
    }
}
